/*
 *  atBudget Personal Finance Management application
 *
 *  Copyright 2011, Ilia Frenkel <frenkel.ilia@gmail.com>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
	Payees controller handles all interactions with payees.
 */
Ext.define('ATB.controller.Payees', {
    extend: 'Ext.app.Controller',
	views: [
		'payee.List',
		'payee.Create',
		'payee.Edit',
		'payee.Manage'
	],
	stores: [
		'Payees'
	],
	models: [
		'Payee'
	],
	/*
		Setup event handlers.
	*/
    init: function() {
		this.control({
			'payeelist': {
				itemdblclick: this.editPayee
			},
			'payeemanage payeelist': {
				selectionchange: this.setButtonsState
			},
			'payeemanage': {
				show: this.refreshStore
			},
			'payeemanage button[action=editpayee]': {
				click: this.openEditPayee
			},
			'payeemanage button[action=addpayee]': {
				click: this.openNewPayee
			},
			'payeemanage button[action=deletepayee]': {
				click: this.deletePayee
			},
			'payeeedit button[action=save]': {
				click: this.updatePayee
			},
			'payeecreate button[action=save]': {
				click: this.createPayee
			}
		});//this.control
    },//init

	/*
		Open edit payee dialogue and load payee information.
		This is an event handler for payees list double click action.
		Parameters:
			grid   - grid panel that the user double clicked
			record - currency record that the user double clicked on
	*/
	editPayee: function(grid, record) {
		var view = Ext.widget('payeeedit');
		view.down('form').loadRecord(record);
	},//editPayee

	/*
		The same as editPayee but for "Edit" button on the toolbar.
		Since we don't have reference to the grid or selected record
		we have to find out which record is selected and then call 
		editPayee method. If no records are selected an error message
		will be shown.
	*/
	openEditPayee: function (button) {
		var win  = button.up('window'),
			grid = win.down('payeelist'),
			sel  = grid.getSelectionModel(),
			recs = sel.selected;
			if (recs.items.length <= 0) {
				Ext.Msg.alert('Error', 'Please select one of the payees first.');
			} else {
				this.editPayee(grid, recs.items[0]);
			}
	},//openEditPayee

	/*
		Open new payee dialogue. Nothing exciting here - just create
		the view.
	*/
	openNewPayee: function() {
		var view = Ext.widget('payeecreate');
	},//openNewPayee

	/*
		An event handler for "Save" button in the edit payee dialogue.
		Collects the values from the form, updates the record and calls
		sync on the store which triggers communication with the server.
		Any error during the communication is handled by the model's proxy.
	*/
	updatePayee: function(button) {
		var win    = button.up('window'),
			form   = win.down('form'),
			record = form.getRecord(),
			values = form.getValues();

		record.set(values);
		this.getPayeesStore().sync();
		record.commit();
		win.close();
	},//updatePayee
	
	/*
		An event handler for "Save" button in the create payee dialogue.
		Collects the values from the form, create new record, adds it to
		the store and calls	sync on the store which triggers communication
		with the server. Any error during the communication is handled by 
		the model's proxy.
	*/
	createPayee: function(button) {
		var win    = button.up('window'),
			form   = win.down('form'),
			values = form.getValues(),
			store  = this.getPayeesStore();

		var record = this.getPayeeModel().create(values);

		store.add(record);
		store.sync();
		win.close();
	},//createPayee

	/*
		An event handler for "Remove" button in the manage payee dialogue.
		Asks for confirmation and if positive destroys the selected record.
		Any error during the communication is handled by the model's proxy.
	*/
	deletePayee: function(button) {
		var win    = button.up('window'),
			grid = win.down('payeelist'),
			sel  = grid.getSelectionModel(),
			recs = sel.selected;
		if (recs.items.length <= 0) {
			Ext.Msg.alert('Error', 'Please select one of the payees first.');
		} else {
			var record = recs.items[0];
			Ext.Msg.show({
				title:'Are you sure?',
				msg: 'Are you sure you want to delete this payee?',
				buttons: Ext.Msg.YESNO,
				fn: function(buttonId) {
					if (buttonId == 'yes') {
						record.destroy();
					}
				},
				icon: 'atb-icon-question'
			});
		}
	},//deletePayee

	/*
		Event handler for payee list. Disables/enables "Edit" and "Remove"
		buttons according to selection.
	*/
	setButtonsState: function(view, sel, opts) {
		var win    = view.view.up('window'),
			edtBtn = win.down('button[action=editpayee]'),
			delBtn = win.down('button[action=deletepayee]')
		if (sel.length > 0) {
			edtBtn.enable();
			delBtn.enable();
		} else {
			edtBtn.disable();
			delBtn.disable();
		}
	},//setButtonsState
	
	/*
		Refresh payees store when manage payees dialogue is shown to
		fetch any changes from the server before we make new ones.
	*/
	refreshStore: function() {
		this.getPayeesStore().load();
	}//refreshStore
});